const { sqlite3 } = require('../../mysql')
const tools = require('../../utlis/tools')
const config = require('../../config')
const secret = config.jwt_config.secretKey
const expiresIn = config.jwt_config.expiresIn
const jwt = require('jsonwebtoken')
const util = require('util')
const verify = util.promisify(jwt.verify) // 解密


const login = async (ctx) => {
  // console.log('开始登录', ctx.request.body)
  const { username, password } = ctx.request.body;
  const data = await sqlite3('user').where({
    username
  }).select()
  // console.log('data:', data)
  if (data.length === 0) {
    ctx.body = {
      code: 0,
      data: {},
      meta: {
        status: 500,
        message: '该用户不存在!'
      }
    }
  } else {
    let payload = {
      id: data[0].id,
      username: data[0].username,
      avatar: data[0].avatar,
    }
    // console.log(data[0].id)
    let id = data[0].id
    await sqlite3('user').where({ id })
      .update({ loginTime: tools.GMTtoStr(new Date()) }) // 修改数据库登录时间
    // 生成access-token
    const token = await tools.signToken(payload, secret, expiresIn)
    if (data[0].passwrod === tools.md5(password) && data[0].status === 1) {
      ctx.body = {
        data: {
          token,
          avatar: data[0].avatar,
          roles: [data[0].roles],
          username: data[0].username
        },
        success: true
      }
    } else if (data[0].passwrod === tools.md5(password) && data[0].status === 0) {
      ctx.body = {
        code: 500,
        meta: {
          status: 500,
          message: `${username}账号已被禁用,请联系管理员!`
        }
      }
    } else {
      ctx.body = {
        code: 500,
        meta: {
          status: 500,
          message: '登录密码错误!'
        }
      }
    }
  }
}

const userList = async (ctx) => {
  let formData = ctx.query
  let offset = (formData.currentPage - 1) * formData.pageSize
  let limit = formData.pageSize
  let keyword = formData.title
  const data = await sqlite3('user').select()
  console.log('data:', data)
  total = data.length
  if (data) {
    ctx.body = {
      success: true,
      data: {
        list: data,
        total,
        pageSize: Number(limit),
        currentPage: Number(formData.currentPage)
      },
    }
  } else {
    ctx.body = {
      success: false
    }
  }
}

const userInfo = async (ctx) => {
  // 获取jwt
  const token = ctx.header.authorization
  if (token) {
    // 解密，获取payload
    const payload = await verify(token.split(' ')[1], secret)
    const data = await sqlite3('user').where({
      username: payload.username,
    }).select()
    // console.log(data);
    if (data) {
      ctx.body = {
        code: 200,
        data: {
          username: data[0].username,
          roles: [data[0].roles],
          avatar: data[0].avatar
        },
        result: true,
      }
    } else {
      ctx.body = {
        result: false,
      }
    }
  }
}


const logout = async (ctx) => {
  ctx.body = {
    code: 200,
    data: 'success'
  }
}


module.exports = { login, userList, userInfo, logout }
